﻿using AutoMapper;
using B.S.GridManage.Api.Write.Application.Command.PhsicalGrid;
using B.S.GridManage.Domain.Entities;
using B.S.GridManage.ErrorCode;
using B.S.GridManage.Infrastructure.Interface;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.GridManage.Api.Write.Application.Handler.PhsicalGrid
{
    /// <summary>
    /// 添加物理网格的处理类
    /// </summary>
    public class CreatePhysicalGridHandler : IRequestHandler<CreatePhysicalGridCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<PhysicallGridModel> physicalGridRepo;
        private readonly IMapper mapper;
        private readonly ILogger<CreatePhysicalGridHandler> logger;

        public CreatePhysicalGridHandler(IBaseRepository<PhysicallGridModel> physicalGridRepo,IMapper mapper,ILogger<CreatePhysicalGridHandler> logger)
        {
            this.physicalGridRepo = physicalGridRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 添加物理网格的处理方法
        /// </summary>
        /// <param name="request">物理网格请求命令表单</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>响应包装类</returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> Handle(CreatePhysicalGridCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();//实例化响应包装类
            //唯一性校验
            var model = physicalGridRepo.GetAll().Where(x => x.GridName == request.GridName).FirstOrDefault();
            if (model != null) {
                res.Msg = "您要添加的网格已经存在!";
                res.Code = ApiEnum.Failed;
                return res;
            }

            model = mapper.Map(request,model);//把命令转换为实体
            model.Id = YitIdHelper.NextId();

            int r = await physicalGridRepo.CreateAsync(model);//使用仓储的添加方法,把物理网格实体添加到数据库中

            if (r > 0)
            {
                res.Msg = "添加物理网格成功!";
                res.Code = ApiEnum.Success;
                res.Data = r;
            }
            else
            {
                res.Msg = "添加物理网格失败!";
                res.Code = ApiEnum.Failed;
                res.Data = r;
            }
            return res;
        }
    }
}
